﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Lab_Report_Search_Tool
{
    public class PdfMerger
    {
        string path;
        string filename;
        string[] urlList;
        
        public PdfMerger(string[] urls, string fname)
        {
            urlList = urls;
            filename=fname;
            path = getTempPath();
        }
         
        public PdfMerger(string[] urls, string fname, string p)
        {
            urlList = urls;
            filename=fname;
            path = p;
        }

        public string getTempPath()
        {
            string Timestamp = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
            //String dir = "\\\\sbs1\\Shared\\Temp\\" + Timestamp + "\\";
            string dir = Path.GetTempPath() + Timestamp + "\\";

            return dir;
        }

        public string getName
        {
            get
            {
                return filename;
            }
        }

        public string getFullPath
        {
            get
            {
                return path+"/"+filename;
            }
        }

        public int Merge()
        {
            if (download() == 0)
            {
                string[] lstFiles = Directory.GetFiles(this.path, "*.pdf");
                for (int y = 0; y < lstFiles.Count(); y++)
                {
                    Console.WriteLine(lstFiles[y]);
                }

                PdfReader reader = null;
                Document sourceDocument = null;
                PdfCopy pdfCopyProvider = null;
                PdfImportedPage importedPage;
                string outputPdfPath = this.getFullPath;


                sourceDocument = new Document();
                pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

                //Open the output file
                sourceDocument.Open();

                try
                {
                    //Loop through the files list
                    for (int f = 0; f < lstFiles.Length; f++)
                    {
                        //MessageBox.Show(lstFiles[f]);
                        int pages = get_pageCcount(lstFiles[f]);

                        reader = new PdfReader(lstFiles[f]);
                        PdfReader.unethicalreading = true;
                        //Add pages of current file
                        for (int i = 1; i <= pages; i++)
                        {
                            importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                            pdfCopyProvider.AddPage(importedPage);
                        }

                        reader.Close();
                        File.Delete(lstFiles[f]);
                    }
                    //At the end save the output file
                    sourceDocument.Close();
                }
                catch (Exception ex)
                {
                    //throw ex;
                    return -1;
                }
                return 0;
            }
            return -2;

           
        }

        private int download()
        {
            if (this.urlList.Length <= 0)
            {
                return -1; 
            }
            System.IO.Directory.CreateDirectory(this.path);
            for (int i = 0; i < this.urlList.Length ; i++)
            {
                Process scriptProc = new Process();
                scriptProc.StartInfo.FileName = Path.Combine(Environment.CurrentDirectory, @"../../saver2.vbs");
                scriptProc.StartInfo.Arguments = "\"" + this.urlList[i].ToString().Split(',')[0] + "\" \"" + i.ToString("0000000000") + "\" \"" + this.path + "\"";
                scriptProc.StartInfo.UseShellExecute = true;
                scriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                scriptProc.Start();
                scriptProc.WaitForExit();
                scriptProc.Close();
            }
            return 0;
        }

        public int get_pageCcount(string file)
        {
            using (StreamReader sr = new StreamReader(File.OpenRead(file)))
            {
                Regex regex = new Regex(@"/Type\s*/Page[^s]");
                MatchCollection matches = regex.Matches(sr.ReadToEnd());

                return matches.Count;
            }
        }
    }
}
